var opn = require("opn"); // 打开浏览器
var express = require("express"); // express框架
var webpack = require("webpack"); // 核心模块webpack
const chalk = require("chalk");
const ora = require("ora");
const httpProxy = require("http-proxy-middleware");
const portfinder = require("portfinder");
var webpackConfig = require("../webpack.config"); // 配置文件
var app = express();
var compiler = webpack(webpackConfig);
const { sort } = require("liu-commonjs-utils");
console.log(sort);

// var http = require("http");
// var sockjs = require("sockjs");
// var echo = sockjs.createServer();
// echo.on("connection", function (conn) {
//   console.log(conn, "conn");
//   conn.on("data", function (message) {
//     console.log(message);

//     conn.write(message);
//   });
//   conn.on("close", function () {});
// });

// var server = http.createServer(app);
// echo.installHandlers(server, { prefix: "/echo" });
// server.listen(9999, "127.0.0.1");
const FriendlyErrorsWebpackPlugin = require("friendly-errors-webpack-plugin");
var devMiddleware = require("webpack-dev-middleware")(compiler, {
  publicPath: webpackConfig.output.publicPath,
  stats: "errors-only" // 可选 注释 细节省略
  //   quiet: true
});
var hotMiddleware = require("webpack-hot-middleware")(compiler, {
  log: false,
  heartbeat: 2000
});
app.use(require("connect-history-api-fallback")());
// 开启 支持history路由
app.use(devMiddleware); // 服务器webpack插件
app.use(hotMiddleware); // 热加载自动打包
app.use(
  httpProxy.createProxyMiddleware("/dev-api", {
    target: "http://localhost:5001",
    changeOrigin: true,
    pathRewrite: {
      ["^/dev-api"]: "/dev-api"
    }
  })
);
let sta = process.cwd();
app.use("/static", express["static"](`${sta}/static`));

async function start() {
  let port = await portfinder.getPortPromise({ port: 8000, stopPort: 9000 });
  var uri = "http://localhost:" + port;
  if (process.env.NODE_ENV !== "production") {
    opn(uri);
  }
  devMiddleware.waitUntilValid(() => {
    const spinner = ora();
    spinner.succeed(
      chalk.green(`应用已启动:${webpackConfig.devServer.host}:${port}`)
    );
    spinner.succeed(chalk.green("欢迎使用 liu-cli --liuyong"));
    webpackConfig.plugins.push(
      new FriendlyErrorsWebpackPlugin({
        compilationSuccessInfo: {
          messages: [`应用已启动:${webpackConfig.devServer.host}:${port}`],
          notes: ["欢迎使用 liu-cli --liuyong"]
        }
      })
    );
  });
  app.listen(port, function() {
    const spinner = ora();
    spinner.succeed(chalk.green("start dev server success"));
  });
}

module.exports = {
  close: () => {
    server.close();
  },
  start
};
